package com.pvdnc.encrypt;

public class Xor implements IEncrypt {

    private static final byte[] DEFAULT_KEY="transdemo".getBytes();

    private static byte[] xorImpl(byte[] data, byte[] key) {
        int keyIndex = 0;
        for (int i = 0; i < data.length; i++) {
            data[i] = (byte) (data[i] ^ key[keyIndex]);
            keyIndex++;
            if (keyIndex == key.length)
                keyIndex = 0;//循环key
        }
        return data;
    }

    private byte[] mKey;

    public void setKey(byte[] key){
        if(key==null)
            key=DEFAULT_KEY;
        mKey=key;
    }

    public Xor(byte[] key){
        setKey(key);
    }

    @Override
    public byte[] encrypt(byte[] rawData) {
        return xorImpl(rawData,mKey);
    }

    @Override
    public byte[] decrypt(byte[] encData) {
        return xorImpl(encData,mKey);
    }
}
